<template>
  <el-dialog v-model="visible" :title="form.id ? '编辑作品' : '新增作品'" width="600px">
    <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>

      <el-form-item label="项目分类" prop="category_id">
        <el-select v-model="form.category_id" placeholder="选择分类">
          <el-option v-for="(val, ind) in categories" :key="ind" :label="val.name" :value="val.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="技术栈" prop="tech_stack_ids">
        <el-select v-model="form.tech_stack_ids" multiple placeholder="选择技术栈">
          <el-option
            v-for="item in techStacks"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="平台分类" prop="platform_ids">
        <el-select v-model="form.platform_ids" multiple placeholder="选择技术栈">
          <el-option
            v-for="item in platforms"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number v-model="form.price" :min="0" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input type="textarea" v-model="form.description" rows="4" />
      </el-form-item>

      <el-form-item label="作品图">
        <el-upload
          :action="uploadUrl"
          :headers="uploadHeaders"
          :on-success="handleUploadSuccess"
          :on-remove="handleRemove"
          list-type="picture-card"
          :file-list="fileList"
          :multiple="true"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getTechStacks } from '@/api/techstack'
import { getCategories } from '@/api/categories'
import { getPlatform } from '@/api/platform'
import { createProduct, updateProduct } from '@/api/products'
import { useUserStore } from '@/stores/user'

const serverBaseUrl = import.meta.env.VITE_API_BASE_URL;

const userStore = useUserStore();
const props = defineProps({
  product: Object,
  modelValue: Boolean,
})
const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const form = ref({
  id: null,
  title: '',
  category: '',
  price: 0,
  description: '',
  tech_stack_ids: [],
  platform_ids: [],
  images: []
})
const formRef = ref()
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  category: [{ required: true }],
  price: [{ required: true }],
}

const techStacks = ref([]);
const categories = ref([]);
const platforms = ref([]);
const fileList = ref([])

const uploadUrl = '/api/product-images/upload'
const uploadHeaders = { Authorization: `Bearer ${userStore.token}` }

const handleUploadSuccess = (res) => {
  form.value.images.push(res.data.url)
  console.log(form.value.images)
}

const handleRemove = (file) => {
  console.log(file);
  // 可选：调用后端删除图片接口
  const fileUrl = file.url.replace(serverBaseUrl, '');
  form.value.images = form.value.images.filter((url) => url !== fileUrl)
}

const submitForm = async () => {
  await formRef.value.validate()
  const isEdit = !!form.value.id
  isEdit
    ? await updateProduct(form.value)
    : await createProduct(form.value)
  ElMessage.success(`${isEdit ? '修改' : '创建'}成功`)
  emit('update:modelValue', false)
  emit('success')
}

watch(() => props.modelValue, async (val) => {
  console.log('监听到变化了', val)
  visible.value = val
  if (val) {
    if (props.product) {
      form.value = { ...props.product }
      form.value.images = props.product.images || []
      fileList.value = props.product.images?.map((url) => ({
        name: url.split('/').pop(),
        url: url.startsWith('http') ? url : `${serverBaseUrl}${url}`
      })) || []
    } else {
      form.value = {
        id: null,
        title: '',
        category: '',
        price: 0,
        description: '',
        tech_stack_ids: [],
        images: []
      }
      fileList.value = []
    }
    const techStacksRes = await getTechStacks()
    techStacks.value = techStacksRes.data;
    const categoriesRes = await getCategories();
    categories.value = categoriesRes.data;
    const platformsRes = await getPlatform();
    platforms.value = platformsRes.data;
  }
}, { immediate: true })

watch(visible, (val) => {
  if (!val) emit('update:modelValue', false)
})
</script>
